﻿// ------------------------------------------------------------------------------------------------
//  <copyright file="Search.cs" company="Iveely">
//    Copyright (c) Iveely Liu.  All rights reserved.
//  </copyright>
//  
//  <Create Time>
//    12/03/2012 20:12 
//  </Create Time>
//  
//  <contact owner>
//    liufanping@iveely.com 
//  </contact owner>
//  -----------------------------------------------------------------------------------------------

#region

using System;
using System.Collections.Generic;
using System.Globalization;
using IveelySE.Common;
using IveelySE.Common.Html;
using IveelySE.Config;
using IveelySE.IDFS.Store;
using IveelySE.Liquidate;
using IveelySE.NLP.Segment;
using IveelySE.NLP.Recognition;

#endregion

namespace IveelySE.Index
{
    /// <summary>
    ///   搜索
    /// </summary>
    public class Search
    {
        #region 属性或字段

        /// <summary>
        /// 分词组件
        /// </summary>
        private static Participle _participle;

        /// <summary>
        /// 显示结果个数
        /// </summary>
        private static readonly int ResultCount = IveelySE.Config.Application.GetResultCount();

        #endregion

        #region 公有方法

        /// <summary>
        ///   初始化搜索项
        /// </summary>
        public static void Init()
        {
            Block.LoadStoreInfo(Application.GetDataDir() + "Page");
            if (_participle == null)
            {
                _participle = Participle.GetInstance();
            }
            Memery.Load();
        }

        /// <summary>
        ///   获取结果
        /// </summary>
        /// <param name="inputs"> 用户输入的查询 </param>
        /// <returns> 搜索结果 </returns>
        public static string GetResult(string inputs)
        {
            //是否命中缓存
            string result = Cache.Match(inputs);
            if (result.Length > 4)
            {
                return result;
            }
            string[] keys = Participle.GetInstance().Split(inputs).Split('/');
            //过滤停用词
            keys = StopWords.Process(keys);
            if (result.Length == 4)
            {
                result = string.Empty;
            }
            try
            {
                Information information = GetKnowlegeResult(keys);
                if (information != null)
                {
                    information.Describution = ChangeColor(keys, CheckContent(information.Describution, keys));
                    result += information.FormatString();
                }
            }
            catch (Exception)
            {

            }

            // 获取全文索引搜索结果
            result += GetFullTextResult(keys);
            Cache.Join(inputs, result);
            return result;
        }

        #endregion

        #region 私有方法

        private static Information GetKnowlegeResult(string[] keys)
        {
            IList<double> KnownlegeIds = Memery.GetKnowledgeBywords(keys);
            return Memery.GetKnowledgeByIds(KnownlegeIds);
        }

        private static string GetFullTextResult(string[] keys)
        {
            int showCount = ResultCount;
            IList<double> list = Memery.GetDocumentByKeywords(keys);
            var pages = new List<string>();
            if (list != null)
            {
                //去除重复表
                var repeate = new HashSet<double>();
                foreach (double d in list)
                {
                    try
                    {
                        if (showCount-- < 1)
                        {
                            break;
                        }

                        object obj = DataService.LocalReadWhenSearch((int)(d), "Page").Value;
                        if (obj == null)
                        {
                            continue;
                        }
                        var page = (Page)obj;
                        //网页去除重复操作
                        if (page == null || repeate.Contains(page.Url.GetHashCode()))
                        {
                            continue;
                        }
                        repeate.Add(page.Url.GetHashCode());
                        //获取文本摘要
                        page.Content = CheckContent(page.Content, keys);
                        //更换标题颜色
                        page.Title = ChangeColor(keys, page.Title);
                        pages.Add(page.ToString());
                    }
                    catch
                    { }
                }
            }
            return string.Join("", pages.ToArray());
        }

        private static int GetInteger(double value)
        {
            return (int)(value * Math.Pow(10, value.ToString(CultureInfo.InvariantCulture).Length - 2));
        }

        /// <summary>
        ///   节选文本中的摘要数据
        /// </summary>
        /// <param name="content"> 文本内容 </param>
        /// <param name="keys"> 关键字集合 </param>
        /// <returns> 返回摘要 </returns>
        private static string CheckContent(string content, string[] keys)
        {
            string text = content;
            string[] matchtext = keys;
            string result = "";
            int chidLen = 80 / matchtext.Length;
            var place = new SortedList<int>();
            foreach (string s in matchtext)
            {
                place.Add(text.IndexOf(s, StringComparison.Ordinal));
            }
            //place.Sort();
            int lastEnd = 0;
            for (int i = 0; i < place.Count; i++)
            {
                int start = place[i] > chidLen / 2 ? place[i] - chidLen / 2 : 0;
                while (start < lastEnd)
                {
                    start++;
                }

                int end = place[i] < text.Length - chidLen / 2 ? place[i] + chidLen / 2 : text.Length;
                if (end - start > keys[i].Length)
                {
                    result += text.Substring(start, end - start) + "  ";
                }
                else if (end - lastEnd > chidLen / 2)
                {
                    result += text.Substring(lastEnd, end - lastEnd);
                }
                lastEnd = end;
            }
            //更换颜色
            result = ChangeColor(keys, result);
            return result;
        }

        /// <summary>
        ///   替换颜色
        /// </summary>
        /// <param name="keys"> 关键字 </param>
        /// <param name="result"> 结果 </param>
        private static string ChangeColor(string[] keys, string result)
        {
            foreach (string key in keys)
            {
                if (key != "")
                {
                    result = result.Replace(key, "<b>" + key + "</b>");
                }
            }
            return result;
        }

        #endregion
    }
}